package com.example.zeon;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
	
	private final static String DATABASE_NAME = "zeon_db";
	private final static int DATABASE_VERSION = 1;
	private final static String TABLE_NAME = "t_user";
	public final static String FIELD_ID="uid"; 
	public final static String FIELD_NAME="name";	
	public final static String FIELD_PWD="password";
	
	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		String sql = "create table "+TABLE_NAME+"("+FIELD_ID+" integer primary key autoincrement,"+FIELD_NAME+" text,"+FIELD_PWD+" text);";
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
        String sql=" DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execSQL(sql);
        onCreate(db);		
	}
	
	public long insert(String name, String pwd) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues(); 
        cv.put(FIELD_NAME, name);
        cv.put(FIELD_PWD, pwd);
        long row = db.insert(TABLE_NAME, null, cv);
        return row;
    }	

	public void delete(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        String whereClause = FIELD_ID+"=?";
        String[] whereValue = {Integer.toString(id)};
        db.delete(TABLE_NAME, whereClause, whereValue);
    }
	
	public void update(int id, String name, String pwd) {
        SQLiteDatabase db = this.getWritableDatabase();
        String whereClause = FIELD_ID+"=?";
        String[] whereValue = {Integer.toString(id)};
        ContentValues cv = new ContentValues(); 
        cv.put(FIELD_NAME, name);
        cv.put(FIELD_PWD, pwd);
        db.update(TABLE_NAME, cv, whereClause, whereValue);
    }	
	
	public Cursor select() {
        SQLiteDatabase db = this.getReadableDatabase();
        //Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null,  " _id desc");
        Cursor c = db.rawQuery("select * from "+DATABASE_NAME, null);
        return c;
    }	
}
